package tool

import (
	"math"
	"strconv"
	"strings"
)

type Paginator struct {
	item        []map[string]interface{} //数据集
	currentPage int                      //当前页
	lastPage    int                      //最后一页
	total       int                      //数据总数
	listRows    int                      //每页数量
	hasMore     bool                     //是否有下一页
	options     map[string]interface{}   //分页配置
	currentPageResolver    int   //



}

func (pag Paginator) Create(

	item []map[string]interface{},
	listRows int,
	currentPage int,
	total int,
	options map[string]interface{}) Paginator {

	pag.options = map[string]interface{}{
		"var_page": "page",
		"path":     "/",
		"query":    map[string]interface{}{},
		"fragment": "",
	}
	for key, val := range options {
		pag.options[key] = val
	}

	if pag.options["path"] != "/" {
		pag.options["path"] = strings.TrimRight(pag.options["path"].(string), "/")
	}

	pag.listRows = listRows

	pag.total = total
	pag.lastPage = int(math.Ceil(float64(total / listRows)))
	pag.currentPage = pag.setCurrentPage(currentPage)
	pag.hasMore = pag.currentPage < pag.lastPage
	pag.item = item

	return pag

}

func (pag Paginator) setCurrentPage(currentPage int) int {
	if pag.currentPage > pag.lastPage {
		if pag.lastPage > 0 {
			return pag.lastPage
		}
		return 1
	}
	return currentPage
}

func (pag Paginator) url(page int) string {
	if page < 0 {
		page = 1
	}
	parameters := map[string]string{}
	path := ""
	if !strings.Contains(pag.options["path"].(string), "[PAGE]") {
		parameters[pag.options["var_page"].(string)] = strconv.Itoa(page)
		path = pag.options["path"].(string)
	}else{
		path = strings.Replace(pag.options["path"].(string),"[PAGE]",strconv.Itoa(page),1)
	}

	if _ ,ok := pag.options["query"].(map[string]interface{}); ok  {
		for key, val := range parameters {
			pag.options["query"].(map[string]interface{})[key] = val
		}
	}

	url := path
	if len(parameters) > 0 {
		url = url + "?" + HttpBuildQuery(parameters)
	}

	return url
}

func (pag Paginator) getUrlRange (start int,end int ) []string{

	urls := make([]string,0)

	for page := start; page <= end; page++ {
		tempUrl := pag.url(page)
		urls = append(urls,tempUrl);
	}
	return urls;
}
